package service

import (
	"xdingtec.cn/xdkaika/app"
	"xdingtec.cn/xdkaika/app/http/api/validator/card_template"
	"xdingtec.cn/xdkaika/app/models"
	"xdingtec.cn/xdkaika/utils/pagination"
)

type CardTemplateService struct {
}

func (CardTemplateService) Get(id uint) (*models.CardTemplateModel, error) {
	m := &models.CardTemplateModel{}
	err := app.DB.Where("id = ?", id).First(&m).Error
	if err != nil {
		return nil, err
	}
	return m, nil
}

func (s *CardTemplateService) Create(m *models.CardTemplateModel) (*models.CardTemplateModel, error) {
	err := app.DB.Create(&m).Error
	if err != nil {
		return nil, err
	}
	return m, nil
}

func (s *CardTemplateService) GetPage(f *card_template.PageForm) (*pagination.JsonPage, error) {
	p := &pagination.JsonPage{}
	limit, offset := pagination.GetLimitOffset(f.Page)

	db := app.DB.Model(&models.CardTemplateModel{})
	if f.Title != "" {
		db.Where("title LIKE ?", "%"+f.Title+"%")
	}
	err := db.Count(&p.Total).Error
	if err != nil {
		return nil, err
	}
	if p.Total == 0 {
		return p, nil
	}
	p.TotalPage = pagination.GetTotal(p.Total)
	var list []*models.CardTemplateModel
	err = db.Order("id desc").Limit(limit).Offset(offset).Find(&list).Error
	if err != nil {
		return nil, err
	}
	p.List = list
	return p, nil
}
